<template>
  <a-modal title="任务领取" :width="660" :visible="visible" @ok="handleModalConfirm"
    @cancel="handleModalCancel" :confirm-loading="modalLoading" @after-open="saveFocusedElement" @after-close="restoreFocusedElement">
    <a-form-model ref="form" :model="form" :rules="formRules" :label-col="{ span: 4 }" :wrapper-col="{ span: 20 }">
      <a-form-model-item label="达人信息">
        <a-input style="width: 200px" v-model="form.ks_user" placeholder="请输入" allowClear  />
        <a-button class="editable-add-btn" @click="search" type="primary" style="margin-left: 20px">
          搜索
        </a-button>
      </a-form-model-item>
      <a-form-model-item label="选择达人" prop="master"  v-if="customersListOptions.length > 0">
        <a-select
          v-model="form.master"
          placeholder="请选择达人"
          @change="handleSelectChange"
          
           :defaultOpen="true"
        >
          <a-select-option
            v-for="user in customersListOptions"
            :key="user.id"
            :value="user.id"
          >
            <div style="display: flex; align-items: center">
              <img
                :src="
                  user.portrait
                    ? processImage(user.portrait)
                    : processImage(
                        '/storage/app_icon/20241115/8db41e60976fb7f1210af4e19c2122cb.png'
                      )
                "
                alt="avatar"
                style="
                  width: 30px;
                  height: 30px;
                  margin-right: 8px;
                  border-radius: 50%;
                "
              />
              <span class="nickname">{{ user.nickname }}</span> (ID:
              {{ user.ks_user_id }})
              <span class="delivery_rate"
                >申样交付率: {{ user.delivery_rate }}%</span
              >
            </div>
          </a-select-option>
        </a-select>
      </a-form-model-item>
    </a-form-model>
    
    
  </a-modal>
</template>

<script>
import * as Ajax from '@/api/channel';
import { mapState, mapGetters } from "vuex";
export default {
  props: {
    task_uuid: {
      type: String,
      default: '',
    },
    visible: {
      type: Boolean,
      default: false,
    },
    level_task_commission_rate: {
      type: Number,
      default: 0,
    },
  },
  data() {
    return {
      modalLoading: false,
      form: {
        typeOptions: '',
        secretKey: '',
        channelCode: '',
        ks_user: '',
        loanAssistanceStatus: false,
        price: '',
        shareProfit: undefined,
        type: undefined,
        remark: '',
        master: "",
        
      },
      formRules: {
        ks_user: { required: true, message: '请输入达人信息', trigger: ['blur', 'change'] },
        companyName: { required: true, message: '请输入公司名称', trigger: ['blur', 'change'] },
        price: { required: true, message: '请输入价格', trigger: ['blur', 'change'] },
        shareProfit: { required: true, message: '请选择分润模式', trigger: ['blur', 'change'] },
        type: { required: true, message: '请选择渠道类型', trigger: ['blur', 'change'] },
        master: {
          required: true,
          message: "请选择达人",
          trigger: ["blur", "change"],
        },
      },
      typeOptions: [
        { label: '同业', value: 0 },
        { label: '信息流', value: 1 },
      ],
      shareOptions: [
        { label: '单价', value: 0 },
        { label: '分润', value: 1 },
      ],
      focusedElement: null,
      testInfo:{
        order_count:'',
        commission:'',
        commission2:'',
      },
      tipShow:false,
      customersListOptions: [],
      ks_user_id:'',
      nickname:'',
    };
  },
  computed: {
    ...mapGetters("user", ["getCdnUrl", "getUserInfo"]),
  },
  methods: {
    processImage(imageUrl) {
      if (imageUrl === undefined || imageUrl === null) {
        return ""; // 或者返回一个默认的 URL
      }

      if (!imageUrl.startsWith("http")) {
        return this.getCdnUrl + imageUrl;
      }
      return imageUrl;
    },
    handleModalConfirm() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          // this.modalLoading = true;
          console.log('确定提交');
          
          Ajax.customersAdd({ks_user_id:this.ks_user_id,nickname:this.nickname})
            .then(( res ) => {
              console.log('res.error',res);
              
              if (res.error === 0) {
                console.log('res.error',res);
                
                this.$message.success('领取成功');
                this.$emit('success');
                this.handleModalCancel();
                this.tipShow = false;
              }
            })
            .finally(() => {
              this.modalLoading = false;
            });
        }
      });
    },
    
    handleModalCancel() {
      this.form = this.$options.data().form;
      this.$refs.form.resetFields();
      this.customersListOptions= []
      this.$emit('close');
    },
    saveFocusedElement() {
      this.focusedElement = document.activeElement;
    },
    restoreFocusedElement() {
      if (this.focusedElement) {
        this.focusedElement.focus();
      }
    },
    
    search(){
      console.log('search');
      Ajax.customersSeach({page:1,list_rows:30,ks_user:this.form.ks_user})
        .then((res) => {
          if (res.error === 0) {
            this.customersListOptions= res.data.data;
          }
        })
        .finally(() => {
          this.loading = false;
        });
    },
    getPopupContainer(triggerNode) {
      return triggerNode.parentNode;
    },
    handlePopupScroll(value) {
      const { scrollHeight, scrollTop, clientHeight } = value.target;
      if (scrollHeight - scrollTop === clientHeight && !this.noMoreData) {
        this.get_customersList(this.page);
      }
    },
    async handleSelectChange(value) {
      // 找到所选的达人信息

      const selectedUser = this.customersListOptions.find(
        (user) => user.id === value
      );
      if (selectedUser) {
        console.log("selectedUser", selectedUser);
        this.ks_user_id = selectedUser.ks_user_id;
        this.nickname = selectedUser.nickname;
      } else {
        console.log("未找到对应的达人");
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.table-wrap {
  margin-top: 20px;
  padding-top: 16px;
}

.btn-gruop {
  display: flex;
  justify-content: flex-end;
}

::v-deep .ant-form-item {
  &:last-child {
    margin-bottom: 0;
  }
}
.tips_box {
  padding: 4px;
}
.text{
  // font-size: 16px;
  color: #999999;
  margin: 10px 0;
  // text-align: center;
  span {
    color: #E33B35;
  }
}
.sale {
  display: flex;
  align-items: center;
  margin-left: 4px;
  margin-bottom: 10px;
  div {
    font-size: 14px;
    span {
      color: #E33B35;
    }
  }
}
</style>